from flask import Flask, request, make_response
import argparse

from werkzeug.wrappers import response

app = Flask("apps_zjh_web_http_demo")


@app.route("/", methods=["GET"])
def index():
    return """
    <button onclick="getSendUrlEncodedData()">getSendUrlEncodedData</button>
    <button onclick="postSendUrlEncodedData()">postSendUrlEncodedData</button>
    <button onclick="postSendString()">postSendString</button>
    <button onclick="postSendJSONString()">postSendJSONString</button>
    <button onclick="postSendFormData()">postSendFormData</button>
    <script>
    function getSendUrlEncodedData(){
      let xhr = new XMLHttpRequest;
      xhr.open("get","/?name=apps");
      xhr.send(null);
    }
    function postSendUrlEncodedData(){
      let xhr = new XMLHttpRequest;
      xhr.open("post","/");
      xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      xhr.send("name=apps");
    }
    function postSendString(){
      let xhr = new XMLHttpRequest;
      xhr.open("post","/");
      xhr.send("hello");
    }
    function postSendJSONString(){
      let xhr = new XMLHttpRequest;
      xhr.open("post","/");
      xhr.setRequestHeader("Content-Type","application/json");
      xhr.send(JSON.stringify({name:"apps"}));
    }
    function postSendFormData(){
      let xhr = new XMLHttpRequest;
      let formdata = new FormData;
      formdata.append("name", "apps");
      xhr.open("post","/");
      xhr.send(formdata);
    }
    </script>
    """


@app.route("/", methods=["POST"])
def api():
    print("form", request.form)
    print("args", request.args)
    print("json", request.json)
    print("data", request.data)
    return "hello"


@app.route("/set-cookie")
def cookie():
    res = make_response("hello")
    res.set_cookie("name", "apps", 10)
    res.status_code = 302
    res.headers.add("Location", "/")
    return res


def main():
    parser = argparse.ArgumentParser(
        description='APPS Flask Web Demo.'
    )
    parser.add_argument('-l', '--host', default="")
    parser.add_argument('-p', '--port', default=-1)

    args = parser.parse_args()
    host = args.host
    port = int(args.port)
    app.run(host=host if host else None,
            port=port if port != -1 else None)


if __name__ == "__main__":
    main()
